﻿using System; 
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using SiteUnity.Layers.Application.BaseClasses;
using System.Web.UI.HtmlControls;

namespace SiteUnity.Frame.Modules
{
    [ToolboxData("<{0}:PreLoading runat=server/>")]
    public class PreLoading : BaseWebControl
    {
        string _template = @"<div class='preloadimage'><img src='{0}' alt='' /></div>";

        public Control Container { get; set; }
        public string ImageUrl { get; set; }
        
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (Container == null)
                Container = Page.Form;

            if (string.IsNullOrEmpty(ImageUrl))
                ImageUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "SiteUnity.Frame.Modules.PreLoading.preloader.gif");
        }

        protected override void OnPreRender(EventArgs e)
        {
            string preloadingready = @"$(function () { $('#{0}').PreLoading(); });";

            preloadingready = preloadingready.Replace("{0}", Container.ClientID);

            Page.ClientScript.RegisterStartupScript(typeof(Page), this.ClientID, preloadingready, true);
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            if (Container is HtmlControl)
                ((HtmlControl)Container).Attributes.Add("style", "display: none");

            if (Container is WebControl)
                ((WebControl)Container).Attributes.Add("style", "display: none");

            output.Write(string.Format(_template, ImageUrl));
        }
    }
}
